/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.dialect;

import java.sql.DatabaseMetaData;
import java.sql.SQLException;

import com.jianggujin.dbfly.util.JDatabaseMetaData;
import com.jianggujin.dbfly.util.JExceptionUtils;
import com.jianggujin.dbfly.util.JLinkedEntry;
import com.jianggujin.dbfly.util.JLinkedList;

/**
 * 方言注册器
 * 
 * @author jianggujin
 *
 */
public class JDialectRegistry {
    private final JLinkedList<String, Class<? extends JDialect>> dialectClasses = new JLinkedList<>();

    @SuppressWarnings("unchecked")
    public JDialectRegistry() {
        Class<?>[] classes = { JMySQLDialect.class, JMariaDBDialect.class, JOracleDialect.class,
                JPostgreSQLDialect.class, JH2Dialect.class, JDMDialect.class };
        for (Class<?> clazz : classes) {
            this.dialectClasses.addLast(clazz.getSimpleName(), (Class<? extends JDialect>) clazz);
        }
    }

    /**
     * 获得方言
     * 
     * @param metaData
     * @param required
     * @return
     * @throws SQLException
     */
    public JDialect getDialect(DatabaseMetaData metaData, boolean required) throws SQLException {
        try {
            JDatabaseMetaData databaseMetaData = new JDatabaseMetaData(metaData);
            for (JLinkedEntry<String, Class<? extends JDialect>> dialectClass : dialectClasses) {
                JDialect dialect = dialectClass.getValue().newInstance();
                if (dialect.support(databaseMetaData)) {
                    return dialect;
                }
            }
            return null;
        } catch (Exception e) {
            throw JExceptionUtils.handleException(e);
        }
    }

    public JLinkedList<String, Class<? extends JDialect>> getDialectClasses() {
        return dialectClasses;
    }

}
